<?php

namespace App\Extensions;

use App\Extensions\Form\Field;

/**
 * @method Field\Select         select($column, $label = '')
 */
class Form extends \Encore\Admin\Form
{
    public static $_availableFields = [
        'select' => Field\Select::class,
        'table'  => Field\ETable::class,
    ];
    protected  $is_layer = false;

    public function __construct($model, \Closure $callback = null)
    {
        self::initCustom();
        parent::__construct($model, $callback);
    }

    protected static function initCustom()
    {
        self::$availableFields = array_merge(self::$availableFields, self::$_availableFields);
    }

    public function isLayer()
    {
        $this->is_layer = true;
        $this->setView('admin.layer-form');
        return $this;
    }

    public function setLayerView()
    {
        $this->setView('admin.layer-form');
    }

    public function backSuccess($msg = '操作成功')
    {
        if ($this->is_layer) {
            return back()->withInput(request()->all())->with('success', $msg);
        }
        if ($this->isCreating()) {
            $resourcesPath = $this->resource(0);
        } else {
            $resourcesPath = $this->resource(-1);
        }
        $key = $this->model->getKey();
        return $this->redirectAfterSaving($resourcesPath, $key);
    }

    //自定义返回
    protected function redirectAfterSaving($resourcesPath, $key)
    {
        if ($this->is_layer) {
            return back()->with('success', '操作成功');
        }
        return parent::redirectAfterSaving($resourcesPath, $key);
    }

    public function backErrors($provider, $key = 'default'): \Illuminate\Http\RedirectResponse
    {
        return back()->withInput(request()->all())->withErrors($provider, $key);
    }

    public function backInputErrors($provider, array $input = null, $key = 'default'): \Illuminate\Http\RedirectResponse
    {
        $input = is_array($input) ? $input : request()->all();
        return back()->withInput($input)->withErrors($provider, $key);
    }

    public function backError($msg = '操作失败', $time = 1000)
    {
        if ($this->is_layer) {
            return back()->withInput(request()->all())->with(['error' => $msg, 'time' => $time]);
        }
        if ($this->isCreating()) {
            $resourcesPath = $this->resource(0);
        } else {
            $resourcesPath = $this->resource(-1);
        }
        admin_toastr($msg, 'error');
        return redirect($resourcesPath);
    }

    public function setActionCurrent()
    {
        return $this->setAction(url(request()->getPathInfo()));
    }

    public function backAdminError($message)
    {
        admin_toastr($message, 'error');
        return back();
    }

    public function backAbort($message = 'Not Found', $code = 404): \Illuminate\Http\Response
    {
        return response()->view('errors.' . $code, compact('message', 'code'));
    }

}
